#include <stdio.h>
#include <zconf.h>
#include "utils/net/sock_utils.h"

void str_cli(FILE *fp, int fd) {
    int max_fd;
    fd_set rset;
    int max_length = 1024;

    char send_buffer[max_length], recv_buffer[max_length];
    int file_fd = fileno(fp);
    int n;
    while(1) {
        FD_SET(file_fd, &rset);
        FD_SET(fd, &rset);

        max_fd = file_fd > fd ? file_fd : fd;
        int count = select(max_fd + 1, &rset, NULL, NULL, NULL);

        if (count == 0) {
            continue;
        }

        if (FD_ISSET(file_fd, &rset)) {
            if (fgets(recv_buffer, max_length - 1, fp) != NULL) {
                memcpy(send_buffer, recv_buffer, strlen(recv_buffer));
                if (write(fd, send_buffer, max_length) < 0) {
                    printf("%s", "套接字异常");
                    return;
                }
            }
        }
        if (FD_ISSET(fd, &rset)) {
            if ((n = read(fd, recv_buffer, max_length - 1)) > 0) {
                recv_buffer[n] = '\0';
                printf("%s", recv_buffer);
            } else {
                printf("套接字读取异常");
                return;
            }
        }
    }

}

int main() {
    int fd = connect_to_tcp_server("127.0.0.1", 13011);
    char buf[] = "123456";
    char recv_buf[1024];
//    while (1) {
//        int n = send(fd, buf, strlen(buf), 0);
//        if (n < 0) {
//            break;
//        }
//        printf("send bytes count = %d\n", n);
//        n = read(fd, recv_buf, 1024);
//        printf("%s", recv_buf);
//        sleep(2);
//    }
    str_cli(stdin, fd);
    return 0;
}